package com.gbase8c.dmt.common.exception;

import java.io.PrintWriter;
import java.io.StringWriter;

public class MetadataException extends RuntimeException {

    public MetadataException() {
        super();
    }

    public MetadataException(String message) {
        super(message);
    }

    public MetadataException(String message, Throwable cause) {
        super(message, cause);
    }

    public MetadataException(Throwable cause) {
        super(cause);
    }

    public static MetadataException asMetadataException(String message) {
        return new MetadataException(message);
    }

    public static MetadataException asMetadataException(Throwable cause) {
        if (cause instanceof MetadataException) {
            return (MetadataException) cause;
        }
        return new MetadataException(getMessage(cause), cause);
    }

    public static MetadataException asMetadataException(String message, Throwable cause) {
        if (cause instanceof MetadataException) {
            return (MetadataException) cause;
        }
        return new MetadataException(message, cause);
    }

    private static String getMessage(Object obj) {
        if (obj == null) {
            return "";
        }

        if (obj instanceof Throwable) {
            StringWriter str = new StringWriter();
            PrintWriter pw = new PrintWriter(str);
            ((Throwable) obj).printStackTrace(pw);
            return str.toString();
            // return ((Throwable) obj).getMessage();
        } else {
            return obj.toString();
        }
    }

}
